<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="生产线名称" prop="productLineName">
        <el-input
          v-model="queryParams.productLineName"
          placeholder="请输入生产线名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:model:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:model:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:model:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:model:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="modelList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="产品" align="center" prop="name" />
      <el-table-column
        label="生产线名称"
        align="center"
        prop="productLineName"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:model:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:model:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改工厂建模对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="modelRef" :model="form" :rules="rules" label-width="80px">
        <div style="display: flex">
          <el-form-item label="生产线" prop="productLineName">
            <el-input v-model="form.productLineName" placeholder="请输入生产线" />
          </el-form-item>
          <el-form-item label="产品" prop="name">
            <el-input v-model="form.name" placeholder="请输入产品" />
          </el-form-item>
          <el-button type="primary" @click="reset(),xz = true">选择</el-button>
        </div>
        <div style="display: flex">
          <el-form-item label="产品型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入产品型号" />
          </el-form-item>
          <el-form-item label="产品规格" prop="specification">
            <el-input v-model="form.specification" placeholder="请输入产品规格" />
          </el-form-item>
        </div>
        <el-form-item label="描述" prop="manufacturer">
            <el-input v-model="form.remark" placeholder="请输入描述" />
          </el-form-item>
        <el-divider content-position="center">工厂建模明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="Plus"
              @click="handleAddMesFactoryModelDetail"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDeleteMesFactoryModelDetail"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table :data="mesFactoryModelDetailList" :row-class-name="rowMesFactoryModelDetailIndex" @selection-change="handleMesFactoryModelDetailSelectionChange"
          ref="mesFactoryModelDetail">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column  property="code" label="设备" width="180">
            <template #default="{ row, $index }">
              <el-select
                v-model="row.equipmentId"
                placeholder="请选择"
                @change="handleSelectChange(row, $index)"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column property="code" label="编码" width="150" />
          <el-table-column property="model" label="型号" width="150" />
          <el-table-column
            property="productDate"
            label="生产日期"
            width="150"
          />
          <el-table-column property="batchNo" label="生产批次" width="150" />
          <el-table-column property="manufacturer" label="制造商" width="150" />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择物料 -->
    <el-dialog id="el-dialog" v-model="xz" title="选择物料档案" width="1000">
    <div style="display: flex;">
      <el-tree style="max-width: 600px" :data="datatree" :props="defaultProps" :default-expand-all="true"
            @node-click="handleNodeClick" />
      <div>
        <div style="display: flex; justify-content: center;">
          <el-form-item label="物料编码" prop="code">
            <el-input v-model="form.code" placeholder="请输入物料编码" />
          </el-form-item>
          <el-form-item label="物料名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入物料名称" />
          </el-form-item>
        </div>
        <div style="display: flex;justify-content: center;">
          <el-form-item label="型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="规格" prop="sation">
            <el-input v-model="form.specification" placeholder="请输入规格" />
          </el-form-item>
        </div>
        <el-table @selection-change="handleSelectionChange" :data="wldata" style="width: 100%">
                <el-table-column property="id" label="编号" width="80" />
                <el-table-column property="code" label="物料编码" width="80" />
                <el-table-column property="name" label="物料名称" width="80" />
                <el-table-column property="model" label="型号" width="80" />
                <el-table-column property="specification" label="规格" width="100" />
                <el-table-column property="unit" label="单位" width="80" />
                <el-table-column property="price" label="单价" width="80" />
                <el-table-column property="type" label="类型" width="80" />
                <el-table-column property="remark" label="备注" width="50" />
                <el-table-column label="操作" width="80">
                    <template v-slot="scope">
                        <el-button @click="xzwl(scope.row), xz = false;" style="display: inline; width: 50px;">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
      </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Model">
import {
  listModel,
  getModel,
  delModel,
  addModel,
  updateModel,
  wl,
  selewl,
  up,
} from "@/api/system/model";
import { ref } from "vue";

const { proxy } = getCurrentInstance();

const modelList = ref([]);
const mesFactoryModelDetailList = ref([]);
const open = ref(false);
const xz=ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMesFactoryModelDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const options=ref([]);
const wldata=ref([]);
var code;
const mes_equipment = [
  {
    label: "空闲",
    value: 0,
  },
  {
    label: "使用中",
    value: 1,
  },
  {
    label: "故障",
    value: 2,
  },
];
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialId: null,
    productLineName: null,
  },
  rules: {},
});
const datatree = [
    {
        label: '分类',
        children: [
            {
                label: '成品',
                children: [
                    {
                        label: '燃油车',
                    },
                    {
                        label: '新能源车'
                    }
                ],
            },
            {
                label: '零件',
                children: [
                    {
                        label: '发动机'
                    },
                    {
                        label: '变速箱'
                    },
                    {
                        label: '轮胎'
                    },
                    {
                        label: '电池'
                    },
                    {
                        label: '底盘'
                    },
                    {
                        label: '大灯'
                    },
                    {
                        label: '空调'
                    }, {
                        label: '座椅'
                    }
                ],
            }
        ],
    }
]

const { queryParams, form, rules } = toRefs(data);

/** 查询工厂建模列表 */
function getList() {
  loading.value = true;
  listModel(queryParams.value).then((response) => {
    modelList.value = response.rows;
    console.log(modelList.value);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
  };
  mesFactoryModelDetailList.value = [];
  proxy.resetForm("modelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  wl().then((response) => {
    options.value = response;
    console.log(response);
  });
  open.value = true;
  title.value = "添加工厂建模";
}
function handleSelectChange(row, index) {
    // 处理 select 变化时的逻辑
    console.log(`第 ${index} 行的数据变更为: `, row.id);
    const selectedOption = this.options.find(option => option.id === row.equipmentId);
    if (selectedOption) {
        row.code = selectedOption.code;
        row.model = selectedOption.model;
        row.productDate = selectedOption.productDate;
        row.batchNo = selectedOption.batchNo;
        row.manufacturer = selectedOption.manufacturer;
    }
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  wl().then((response) => {
    options.value = response;
    console.log(response);
  });
  const _id = row.id || ids.value;
  getModel(_id).then((response) => {
   var name = response.data.productLineName;
    let applicant = ref({ id:response.data.materialId });
    const jsonString = JSON.stringify(applicant.value);
    up(jsonString).then((response1) => {
      mesFactoryModelDetailList.value = response.data.mesFactoryModelDetailList;
      for(var i=0;i<response.data.mesFactoryModelDetailList.length;i++){
    const selectedOption = this.options.find(option => option.id === response.data.mesFactoryModelDetailList[i].equipmentId);
    if (selectedOption) {
      mesFactoryModelDetailList.value[i].code = selectedOption.code;
      mesFactoryModelDetailList.value[i].model = selectedOption.model;
      mesFactoryModelDetailList.value[i].productDate = selectedOption.productDate;
      mesFactoryModelDetailList.value[i].batchNo = selectedOption.batchNo;
      mesFactoryModelDetailList.value[i].manufacturer = selectedOption.manufacturer;
    }
       }
      form.value={
        id:row.id,
        productLineName:name,
        name:response1[0].name,
        model:response1[0].model,
        specification:response1[0].specification
      }
    })

    open.value = true;
    title.value = "修改工厂建模";
  });

}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["modelRef"].validate((valid) => {
    if (valid) {
      form.value.mesFactoryModelDetailList = mesFactoryModelDetailList.value;
      if (form.value.id != null) {
        updateModel(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addModel(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除工厂建模编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delModel(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 工厂建模明细序号 */
function rowMesFactoryModelDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 工厂建模明细添加按钮操作 */
function handleAddMesFactoryModelDetail() {
  let obj = {};
  obj.equipmentId = "";
  mesFactoryModelDetailList.value.push(obj);
}

/** 工厂建模明细删除按钮操作 */
function handleDeleteMesFactoryModelDetail() {
  if (checkedMesFactoryModelDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的工厂建模明细数据");
  } else {
    const mesFactoryModelDetails = mesFactoryModelDetailList.value;
    const checkedMesFactoryModelDetails = checkedMesFactoryModelDetail.value;
    mesFactoryModelDetailList.value = mesFactoryModelDetails.filter(function (
      item
    ) {
      return checkedMesFactoryModelDetails.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleMesFactoryModelDetailSelectionChange(selection) {
  checkedMesFactoryModelDetail.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/model/export",
    {
      ...queryParams.value,
    },
    `model_${new Date().getTime()}.xlsx`
  );
}
function handleNodeClick(data) {
    // data 是当前节点的数据对象
    console.log(data.label);
    code = data.label
    wlsele()
}
function wlsele() {
    let applicant = ref({ id: form.id, name: form.name, model: form.model, specification: form.sation, code: code });
    const jsonString = JSON.stringify(applicant.value);
    console.log(jsonString)
    selewl(jsonString).then((response) => {

      wldata.value = response;
             for (var i = 0; i < response.length; i++) {
                 if (wldata.value[i].type == 1) {
                     wldata.value[i].type = "成品"
                 } else {
                     wldata.value[i].type = "原材料"
                 }
             }
    
  });
}
const xzwl = (row) => {
  form.value = {
    wlid: row.id,
    name:row.name,
    model:row.model,
    specification:row.specification
  };
}
getList();
</script>
<style>
.el-tree {
    float: left;
    width: 150px;
}

.el-tree,
.el-tree div {
    display: block;
    justify-content: left !important;
    margin: 0 !important;
}

.el-tree__drop-indicator {
    height: 0px !important;
}
</style>
